import os
import re
import sys

# Add the scripts directory to the path
sys.path.append(os.path.join(os.path.dirname(__file__), 'scripts'))

def test_markdown_tables():
    """
    Test that the Markdown tables in the Workspace files are correctly formatted
    """
    print("Testing Workspace.md table formatting...")
    
    # Test English version
    en_file_path = os.path.join(
        os.path.dirname(__file__),
        'docs', 'Basic Creation Guide', 'Getting Started', 'Using the Maker', 'Workspace', 'Workspace.md'
    )
    
    # Test Chinese version
    zh_file_path = os.path.join(
        os.path.dirname(__file__),
        'docs_zh', 'Basic Creation Guide', 'Getting Started', 'Using the Maker', 'Workspace', 'Workspace.md'
    )
    
    for file_path in [en_file_path, zh_file_path]:
        if not os.path.exists(file_path):
            print(f"❌ File not found: {file_path}")
            continue
        
        print(f"\n📄 Checking: {file_path}")
        
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Check if the MyDesk table exists and is correctly formatted
        if 'MyDesk Context Menu' in content or 'MyDesk環境選單' in content:
            # Find tables in the content
            tables = re.findall(r'((?:.*\|.*\n)+(?:\s*-+\|\s*-+\|\s*-+\s*\n)(?:.*\|.*\n)+)', content)
            
            if not tables:
                print(f"❌ No tables found in the file")
                continue
            
            for i, table in enumerate(tables):
                print(f"\n📊 Table {i+1}:")
                
                # Check table structure
                lines = [line.strip() for line in table.split('\n') if line.strip()]
                
                if len(lines) < 2:
                    print(f"❌ Table is too short: {lines}")
                    continue
                
                # Check header and separator
                header = lines[0]
                separator = lines[1]
                
                # Count columns in header and separator
                header_cols = header.split('|')
                separator_cols = separator.split('|')
                
                # Remove empty columns (if any)
                header_cols = [col for col in header_cols if col.strip()]
                separator_cols = [col for col in separator_cols if col.strip()]
                
                print(f"   Header columns: {len(header_cols)}")
                print(f"   Separator columns: {len(separator_cols)}")
                
                if len(header_cols) != len(separator_cols):
                    print(f"❌ Column mismatch between header and separator")
                    print(f"   Header: {header}")
                    print(f"   Separator: {separator}")
                    continue
                
                # Check each data row
                for j, row in enumerate(lines[2:]):
                    row_cols = row.split('|')
                    row_cols = [col for col in row_cols if col.strip()]
                    
                    print(f"   Row {j+1} columns: {len(row_cols)}")
                    
                    if len(row_cols) != len(header_cols):
                        print(f"❌ Column mismatch in row {j+1}")
                        print(f"   Row: {row}")
                        continue
                
                print(f"   ✅ Table {i+1} has consistent column count")
                
                # Check specific MyDesk Context Menu table
                if 'Create Scripts' in table and ('Create Component' in table or '建立新的腳本元件' in table):
                    print("   ✅ Found MyDesk Context Menu table with nested items")
                    
                    # Check that nested items are properly formatted
                    if 'Create Scripts | Create Component' in table:
                        print("   ✅ Create Component is properly nested under Create Scripts")
                    
                    if 'Import From | Import Scripts' in table:
                        print("   ✅ Import Scripts is properly nested under Import From")
        
        print(f"\n✅ All checks completed for {file_path}")

def test_directory_structure():
    """
    Test that the directory structure is correct for both languages
    """
    print("\nChecking directory structure...")
    
    # Check English directory
    en_dir = os.path.join(
        os.path.dirname(__file__),
        'docs', 'Basic Creation Guide', 'Getting Started', 'Using the Maker', 'Workspace'
    )
    
    # Check Chinese directory
    zh_dir = os.path.join(
        os.path.dirname(__file__),
        'docs_zh', 'Basic Creation Guide', 'Getting Started', 'Using the Maker', 'Workspace'
    )
    
    for lang, dir_path in [('English', en_dir), ('Chinese', zh_dir)]:
        if os.path.exists(dir_path):
            print(f"✅ {lang} directory exists: {dir_path}")
            
            # Check if Workspace.md exists
            md_file = os.path.join(dir_path, 'Workspace.md')
            if os.path.exists(md_file):
                print(f"   ✅ {lang} Workspace.md exists")
            else:
                print(f"   ❌ {lang} Workspace.md not found")
                
            # Check if images directory exists
            images_dir = os.path.join(dir_path, 'images')
            if os.path.exists(images_dir):
                print(f"   ✅ {lang} images directory exists")
            else:
                print(f"   ❌ {lang} images directory not found")
        else:
            print(f"❌ {lang} directory not found: {dir_path}")

if __name__ == "__main__":
    test_markdown_tables()
    test_directory_structure()
    print("\n✅ All tests completed!")
